package com.project.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;
import com.project.result.GlobalHandleException;
import com.project.result.Result;
import com.project.service.IUserService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

import javax.servlet.ServletResponse;
import java.io.IOException;

public class WebUtil {
    /**
     * 将数据以json格式返回给客户端
     * @param response
     * @param result
     * @throws IOException
     */
    public static void writeValueAsString(ServletResponse response, Result result) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(mapper.writeValueAsString(result));
    }

    /**
     * 解密token，解密成功返回用户对象
     * @param token token数据
     * @param userService 用户业务方法
     * @return 如果验证成功返回实例用户，否则返回null
     * @throws GlobalHandleException
     */
    public static UserBean verifyToken(String token, IUserService userService) throws GlobalHandleException {
        //1,当token是null或“”时，直接返回null；
        if(token == null || token.equals("")){
            return null;
        }
        String audience = null;
        try {
            audience = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException e){
            e.printStackTrace();
//            throw new GlobalHandleException(ResultCode.USER_AUTHENTICATION_ERROR);
            //2,当token中无法解析出用户名时，直接返回null；
            return null;
        }
        UserBean userBean = userService.findByName(audience);
        //将密码转换
        Algorithm algorithm =  Algorithm.HMAC256(userBean.getPwd());
        DecodedJWT decodedJWT =  null;
        try {
            JWTVerifier verifier = JWT.require(algorithm).build();
            decodedJWT = verifier.verify(token);
        }catch (Exception e){
            e.printStackTrace();
//            throw new GlobalHandleException(ResultCode.USER_AUTHENTICATION_ERROR)
            //3,当token无法被正确密码解析时，说明密码错误。返回null
            return null;
        }
        //4,最后返回userBean;
        return userBean;
    }

    /**
     * 封装请求信息对象
     * @return
     */
    public static HttpEntity httpEntity() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        headers.add("accept","application/json");
        HttpEntity<HttpHeaders> request = new HttpEntity<>(headers);
        return request;
    }

}
